function ecog=ecogNormalizeTS(ecog,method)
% ecog=ecogNormalizeTS(ecog,normFac) Normalize the ecog time series
%
% PURPOSE:
% Normalize the ecog time series
%
% INPUT: 
% ecog:     An ecog structure with fiels data and nBaselineSamples.
% method:   A string describing the normalization method.
%           DEFAULTS to 'zsore'if second argument is omitted 
%           'zscore': Z-scores each channel individually. 
%           If data field holds one single trial then standard deviation 
%           is calculated from the whole time series.
%           If the data field holds multiple trials then the standard 
%           deviaton s caculated from all baselines but the post-baseline 
%           time series is excluded.
%           
% OUTPUT:
% ecog:     An ecog structure with normalized time series data 
%

% TODO:
% Let user pass the normalization factor
% Include suppor for multiple trials
% 110306 JR wrote it

if nargin==1
    method='zscore';
end

switch method
    case 'zscore'
        if ~isfield(ecog,'nBaselineSamp')
            disp('nBaselineSamp an baselineDur not defined!')
            disp('Seting both to trial length.')
            ecog.nBaselineSamp=size(ecog.data,2);
            ecog.baselineDur=ecog.nBaselineSamp*ecogs.ampDur;
        end
        if size(ecog.data,3)==1 % one single trial: typically huge datset
            baselineOri=ecog.nBaselineSamp;
            ecog.nBaselineSamp=size(ecog.data,2);
            ecog=ecogBaselineCorrect(ecog); %subtract mean from each channel
            for k=1:size(ecog.data,1) 
                ecog.data(k,:)=ecog.data(k,:)/std(ecog.data(k,:));
            end
            ecog.nBaselineSamp=baselineOri;
        elseif size(ecog.data,3)>1; % Multiple trial: parallelize procssing of multiple small chunks
            ecog=ecogBaselineCorrect(ecog); %subtract baseline from each channel
            nBaselineSamp=ecog.nBaselineSamp;
            dataIsSingle=isa(ecog.data,'single');
            for m=1:size(ecog.data,3)
                tmp=double(ecog.data(:,:,m));
                baseTmp=ecog.data(:,1:nBaselineSamp,m);
                parfor k=1:size(tmp,1) 
                    tmp(k,:)=tmp(k,:)/std(baseTmp(k,:));
                end
                if dataIsSingle
                    ecog.data(:,:,m)=single(tmp);
                else
                    ecog.data(:,:,m)=tmp;
                end
            end
        else
            error('Ooops! should never get here! Check third diemnseion of data field.')
        end
            
    otherwise
        disp(['ecogNormalizeTS: method ' method ' not implemented'])
end 
